import React, { Component, useState } from 'react';

import {
    StyleSheet,
    Text,
    View,
    Platform,
    Dimensions,
    TouchableOpacity,
    ScrollView,
    TextInput, Image, DeviceEventEmitter, PermissionsAndroid,
} from 'react-native';
import Constant from '../../utils/Constant'; //全局变量
import Header from '../../components/header';
import HttpUtils from "../../utils/HttpUtils";
import HttpUrls from "../../utils/HttpUrls";
import Loading from '../../utils/Loading';
import RegionPickerView from "../../components/Tool/RegionAllPickerView";
import AndroidModule from "../../utils/AndroidConnent";
import PublishCarPic from "../car/publishCar/components/PublishCarPic";
import {getImgUrl} from "../../utils/ComFunction";
import * as buffer from "buffer";
import {CommonPicker, RegionPicker} from "@yz1311/react-native-wheel-picker";
import ActionSheet from "react-native-actionsheet";
import ImageCropPicker from "react-native-image-crop-picker";
import Upload from "../../components/upload/Upload";
import PermissionDialog from "../../components/dialog/PermissionDialog";
import AsyncImage from "../../components/image/AsyncImage";
import {ToastToUser} from "../../utils/CustomToast";


const isIos = Platform.OS == 'ios';
const screenW = Dimensions.get('window').width;
const screenH = Dimensions.get('window').height;

let navigation;

export default class ApplyCarFormPage extends Component
{
    constructor(props) {
        super(props);
        this.state = {
            formStructureData: [],

            // 选中城市标识
            showCityPicker: false,
            currentCityIdx: null,

            // 区间选择器
            showPicker: false,
            pickerIdx: null,
            pickerDataPr: [],
            pickerData: [],
            pickerInputType: '',

            // 品牌选择标识
            currentBrandIdx: null,

            uploadImgIdx: null,

            dialogVisible: false,

        };
    }

    componentDidMount() {
        this.selectBrandResult = DeviceEventEmitter.addListener('selectBrandResult', (result) => {
            if (result && result.from === 'ApplyCarFormPage') {
                this.formatBrand(result)
            }
        })

        if(this.state.formStructureData.length === 0){
            this.getFormData()
        }

    }

    componentWillUnmount(){
        if (this.selectBrandResult) {
            this.selectBrandResult.remove();
        }
    }

    // 获取表单数据
    getFormData() {
        let params = this.props.route.params;
        console.log('params====', params)
        let id = params?.id
        if(!id){
            id = 0
        }
        this.Loading.show();
        HttpUtils.getRequest(HttpUrls.getCarPurchaseFormData, {carPurchaseId: id})
            .then(result => {
                if(result.code === 0){
                    let data = result.data;
                    if (data) {
                        data.map(item => {
                            if(item.inputType === 'select'){
                                let newOpt = {
                                    label: '不限',
                                    value: '不限',
                                    selected: true
                                }
                                if(item.values.length > 0){
                                    newOpt.selected = false
                                }
                                item.selectOptions.unshift({
                                    label: '不限',
                                    value: '不限',
                                    selected: true
                                });
                            }
                        });
                        this.setState({
                            formStructureData: data
                        })
                    }
                }
            })
            .catch(error => {}).finally(() => {
            this.Loading.hide();
        });
    }

    inputValueChange(text, inputType, typeText, index){
        console.log("inputValueChange === ", text, inputType, typeText, index)
        const newFormStructureData = [...this.state.formStructureData];
        if(inputType === 'input' || inputType === 'textarea'){
            newFormStructureData[index] = {
                ...newFormStructureData[index],
                inputValue: text
            };
        }else if(inputType === 'rangeInput'){
            if(typeText === 'minValue'){
                newFormStructureData[index] = {
                    ...newFormStructureData[index],
                    minValue: text
                };
            }else {
                newFormStructureData[index] = {
                    ...newFormStructureData[index],
                    maxValue: text
                };
            }
        }

        this.setState({ formStructureData: newFormStructureData });
    }

    //求购地区回调处理
    cityPickerData(item) {
        console.log("求购地 === ", item)
        this.setState({
            showCityPicker: false
        })

        let currIdx = this.state.currentCityIdx
        let newFormStructureData = [...this.state.formStructureData];
        // 当前值
        let currData = newFormStructureData[currIdx].values
        let cityData = {}
        if(item.cityName == '不限'){
            cityData = {
                label: item.provinceName,
                value: item.provinceId,
            }
        }else {
            cityData = {
                label: item.cityName,
                value: item.cityId,
            }
        }
        const isDuplicate = currData.some(city => city.value === cityData.value);
        if(!isDuplicate){
            // 创建新数组避免直接修改状态
            let newCurrData = []
            if(newFormStructureData[currIdx].isMultiple === 1){ // 多选
                newCurrData = [...currData, cityData];
            }else {
                newCurrData = [cityData]
            }
            // 更新状态
            newFormStructureData[currIdx] = {
                ...newFormStructureData[currIdx],
                values: newCurrData
            };
            this.setState({
                formStructureData: newFormStructureData
            });
        }
        console.log("cityPickerData === ", newFormStructureData[currIdx])
    }

    // 选中品牌后处理
    formatBrand(item) {
        console.log("选中品牌1", item)
        let currIdx = this.state.currentBrandIdx
        let newFormStructureData = [...this.state.formStructureData];
        // 当前值
        let currData = newFormStructureData[currIdx].values
        let brandData = {}
        // 不限品牌时， 清空
        if(item.brandId > 0){
            if(item.seriesId === 0 || !item.seriesId){ // 不限
                brandData = {
                    label: item.brandName,
                    value: item.brandId,
                }
            }else {
                brandData = {
                    label: item.seriesName,
                    value: item.seriesId,
                }
            }
            const isDuplicate = currData.some(brand =>  brand.value === brandData.value);
            if(!isDuplicate){
                // 创建新数组避免直接修改状态
                let newCurrData = []
                if(newFormStructureData[currIdx].isMultiple === 1){ // 多选
                    newCurrData = [...currData, brandData];
                }else {
                    newCurrData = [brandData]
                }
                // 更新状态
                newFormStructureData[currIdx] = {
                    ...newFormStructureData[currIdx],
                    values: newCurrData
                };
            }
        }else {
            newFormStructureData[currIdx].values = []
        }

        this.setState({
            formStructureData: newFormStructureData
        });

        console.log("selectBrandData === ", this.state.formStructureData[currIdx])
    }
    //选项按钮布局
    selectOptionView(data, itemIdx) {
        return (
            <View key={data.type} style={styles.optionsContainer}>
                {
                    data.values.length > 0 ?
                        data.values.map((option, index) => (
                            <TouchableOpacity activeOpacity={0.8} onPress={() => {
                                this.selectOption(itemIdx, index)
                            }} key={index} >
                                <View style={[styles.optionButton, styles.selectedOption]}>
                                    <Text style={styles.optionText}>{option.label}</Text>
                                </View>
                            </TouchableOpacity>
                        ))
                        :
                        // 仅当 inputType 不为 carModelSelect 时显示"不限"
                        (data.inputType !== 'carModelSelect' && (
                            <View style={[styles.optionButton, styles.selectedOption]}>
                                <Text style={styles.optionText}>不限</Text>
                            </View>
                        ))
                }

            </View>
        )
    }
    selectOption(itemIdx, optionIdx){
        console.log('selectOption', itemIdx, optionIdx)
        let newFormStructureData = [...this.state.formStructureData];
        let currData = newFormStructureData[itemIdx].values
        if(currData.length > 0){
            currData.splice(optionIdx, 1)
            this.setState({
                formStructureData: newFormStructureData
            });
        }
        console.log("删除select选项 === ", newFormStructureData[itemIdx])
    }
    showPickerOption(index, data, typeText){
        let pickerData = []
        data.map(item => {
            pickerData.push(item.label)
        })
        this.setState({
            showPicker: true,
            pickerIdx: index,
            pickerData: pickerData,
            pickerDataPr: data,
            pickerInputType: typeText,
        })
    }
    pickerSure(item){
        this.setState({
            showPicker: false
        })
        let currIdx = this.state.pickerIdx
        let newFormStructureData = [...this.state.formStructureData];
        let currData = newFormStructureData[currIdx].values
        let selectData = {}
        this.state.pickerDataPr.map((pickerItem, pickerIdx) => {
            if(pickerItem.label === item[0]) {
                selectData.label = pickerItem.label
                selectData.value = pickerItem.value
            }
        })
        if(this.state.pickerInputType === 'left'){
            newFormStructureData[currIdx] = {
                ...newFormStructureData[currIdx],
                values: [selectData]
            };
        }
        if(this.state.pickerInputType === 'right'){
            if(currData.length === 0){
                newFormStructureData[currIdx] = {
                    ...newFormStructureData[currIdx],
                    values: [selectData]
                };
            }else {
                newFormStructureData[currIdx].values = [...newFormStructureData[currIdx].values, selectData]
            }
        }

        this.setState({
            formStructureData: newFormStructureData
        });
    }
    pickerCancel(){
        this.setState({
            showPicker: false
        })
    }
    selectOptionBtnView(data, index){
        return (
            <View key={data.type} style={styles.optionsContainer}>
                { data.selectOptions.map((option, opIndex) => (
                    <TouchableOpacity activeOpacity={0.8} onPress={() => {
                        this.selectBtnOption(index, opIndex)
                    }} key={opIndex}>
                        <View style={[styles.optionButton, option.selected ? styles.selectedOption : null]}>
                            <Text style={styles.optionText}>{option.label}</Text>
                        </View>
                    </TouchableOpacity>
                ))}
            </View>
        )
    }
    // 按钮选中逻辑
    selectBtnOption(itemIdx, optindex){
        console.log('selectOptionBtn', itemIdx, optindex)
        let newFormStructureData = [...this.state.formStructureData];
        // 当前值
        let currData = newFormStructureData[itemIdx]
        const option = currData.selectOptions[optindex];

        // 判断是否为"不限"选项
        const isUnlimited = option.value === '不限';

        // 判断当前是单选还是多选 (1=多选, 0=单选)
        const isMultiple = currData.isMultiple === 1;

        // 反转当前选项的选中状态
        currData.selectOptions[optindex].selected = !currData.selectOptions[optindex].selected;

        // 创建去重标识函数
        const isDuplicate = (value) =>
            currData.values.some(item => item.value === value);

        // === 处理"不限"选项的特殊逻辑 ===
        if (isUnlimited) {
            if (currData.selectOptions[optindex].selected) {
                // 选择了"不限"：清空其他所有选项
                currData.values = [{
                    label: option.label,
                    value: option.value
                }];

                // 取消其他所有选项的选中状态
                currData.selectOptions.forEach((opt, idx) => {
                    if (idx !== optindex) opt.selected = false;
                });
            } else {
                // 取消"不限"：直接清空values
                currData.values = [];
            }
        }
        // === 处理普通选项 ===
        else {
            if (currData.selectOptions[optindex].selected) {
                // 添加当前选项
                if (!isDuplicate(option.value)) {
                    currData.values.push({
                        label: option.label,
                        value: option.value
                    });
                }

                // 如果当前是多选：移除"不限"选项
                if (isMultiple) {
                    // 查找并移除"不限"选项
                    currData.values = currData.values.filter(
                        item => item.value !== '不限'
                    );

                    // 取消"不限"的选中状态
                    const unlimitedIndex = currData.selectOptions.findIndex(
                        opt => opt.value === '不限'
                    );
                    if (unlimitedIndex !== -1) {
                        currData.selectOptions[unlimitedIndex].selected = false;
                    }
                }
                // 如果是单选：设置当前为唯一选中项
                else {
                    currData.values = [{
                        label: option.label,
                        value: option.value
                    }];

                    // 取消其他所有选项的选中状态
                    currData.selectOptions.forEach((opt, idx) => {
                        if (idx !== optindex) opt.selected = false;
                    });
                }
            } else {
                // 移除当前选项
                currData.values = currData.values.filter(
                    item => item.value !== option.value
                );
            }
        }

        this.setState({
            formStructureData: newFormStructureData
        })
        console.log('selectBtnOption', newFormStructureData[itemIdx])
    }
    // 图片处理
    selectPhoto(index) {
        if (index === 0) {
            //相册
            const option = { mediaType: "photo", cropping: false, compressImageQuality: .8, multiple: false };
            ImageCropPicker.openPicker(option).then(images => {
                if (this.Loading) {
                    this.Loading.show();
                }
                console.log('images ===> ', images);
                Upload.getAlipz(images.path, Upload.OSS_CAR, this.uploadafterfun);//获取阿里凭证。
            }, (error) => {
                console.log(error);
            });
        } else if (index === 1) {
            //照相机
            if (isIos) {
                this.takePhoto()
            } else {
                PermissionsAndroid.check('android.permission.CAMERA').then(res => {
                    if (!res) {
                        this.setState({
                            dialogVisible: true
                        })
                    }
                    else {
                        this.takePhoto()
                    }
                })
            }
        }
    }

    takePhoto() {
        const option = { mediaType: "photo", cropping: false, compressImageQuality: .8, };
        ImageCropPicker.openCamera(option).then(images => {
            if (this.Loading) {
                this.Loading.show()
            }
            Upload.getAlipz(images.path, Upload.OSS_FACE, this.uploadafterfun);//获取阿里凭证。
        }, (error) => {
            console.log(error);
        });
    }

    uploadafterfun = (bojkey) => {
        if (this.Loading) {
            this.Loading.hide();
        }
        console.log('uploadafterfun', bojkey)
        let index = this.state.uploadImgIdx
        let newFormStructureData = [...this.state.formStructureData];
        let currData = newFormStructureData[index]
        currData.values.push({
            label: bojkey,
            value: bojkey
        })
        this.setState({
            formStructureData: newFormStructureData
        })
        console.log('uploadafterfun', newFormStructureData[index])
        // DeviceEventEmitter.emit('commonEvent', { type: 'ApplyCarFormPage', face: bojkey })
    }

    removeImg(itemIndex, imgIndex) {
        let newFormStructureData = [...this.state.formStructureData];
        // 当前值
        let currData = newFormStructureData[itemIndex].values
        currData.splice(imgIndex, 1)
        this.setState({
            formStructureData: newFormStructureData
        })
    }

    saveCarFrom(){
        this.Loading.show();
        let paramsData = this.props.route.params
        let id = paramsData?.id || null;
        let fromPage = paramsData?.fromPage || null; // 获取来源页面标识
        let params = {
            id: id,
            params: this.state.formStructureData,
            userId: Constant.userInfo.userId,
            buyerId: Constant.userInfo.buyerId,
        }
        HttpUtils.postRequest(HttpUrls.saveCarPurchase, params)
            .then(result => {
                console.log('saveCarFrom', result)
                if(result.code === 0){
                    ToastToUser("保存成功")
                    setTimeout(()=>{
                        navigation.goBack()
                        DeviceEventEmitter.emit('ApplyCarFormPageSave', {
                            fromPage: fromPage,
                        })
                    },500)
                }else {
                    ToastToUser(result.msg ? result.msg : result.message)
                }
            })
            .catch(error => {
                ToastToUser('系统错误')
            }).finally(() => {
            this.Loading.hide();
        });
    }

    render(){
        navigation = this.props.navigation;
        return (
            <View style={styles.container}>
                <Header navigation={navigation} Title={'发布求购'}  />
                <ScrollView
                    showsVerticalScrollIndicator={false}
                    style={styles.scrollContainer}
                    contentContainerStyle={styles.scrollContent}
                    keyboardShouldPersistTaps="handled"
                >
                    {this.state.formStructureData.map((item, index) => {
                        if(item.inputType === 'input'){
                            return (
                                <View key={index} style={styles.inputGroup}>
                                    <Text style={styles.label}>
                                        {/* 添加必填标识 */}
                                        {item.isMust === 1 && <Text style={styles.requiredStar}>* </Text>}
                                        {item.typeText}
                                    </Text>
                                    <TextInput
                                        editable={true}
                                        style={styles.input2}
                                        placeholder={'请输入' + item.typeText}
                                        value={item.inputValue || ""} // 绑定值
                                        maxLength={item.maxLength || 500} // 字数限制
                                        onChangeText={(text) => this.inputValueChange(text, item.inputType, item.typeText, index)}
                                    />
                                    {/*<Text style={styles.inputCharCount}>{item.inputValue.length}/{'100'}</Text>*/}
                                    {item.maxLength > 0 && (
                                        <Text style={styles.inputCharCount}>{item.inputValue.length}/{item.maxLength}</Text>
                                    )}
                                </View>
                            )
                        }
                        if(item.inputType === 'textarea'){
                            return (
                                <View key={index} style={styles.inputGroup}>
                                    <Text style={styles.label}>
                                        {/* 添加必填标识 */}
                                        {item.isMust === 1 && <Text style={styles.requiredStar}>* </Text>}
                                        {item.typeText}
                                    </Text>
                                    <TextInput
                                        editable={true}
                                        style={[styles.input, styles.multilineInput]}
                                        placeholder={'请输入' + item.typeText}
                                        multiline
                                        value={item.inputValue || ""} // 绑定值
                                        onChangeText={(text) => this.inputValueChange(text, item.inputType, item.typeText, index)}
                                    />
                                </View>
                            )
                        }
                        if(item.inputType === 'areaSelect'){
                            return (
                                <View key={index} style={styles.inputGroup}>
                                    <Text style={styles.label}>
                                        {/* 添加必填标识 */}
                                        {item.isMust === 1 && <Text style={styles.requiredStar}>* </Text>}
                                        {item.typeText}
                                    </Text>
                                    {this.selectOptionView(item, index)}
                                    <TouchableOpacity onPress={() => {
                                        this.setState({
                                            showCityPicker: true,
                                            currentCityIdx: index
                                        })
                                    }} style={styles.addSelectButton}>
                                        <Text style={styles.addSelectButtonText}>+ 添加{item.type}</Text>
                                    </TouchableOpacity>
                                </View>
                            )
                        }
                        if(item.inputType === 'carModelSelect'){
                            return (
                                <View key={index} style={styles.inputGroup}>
                                    <Text style={styles.label}>
                                        {/* 添加必填标识 */}
                                        {item.isMust === 1 && <Text style={styles.requiredStar}>* </Text>}
                                        {item.typeText}
                                    </Text>
                                    {this.selectOptionView(item, index)}
                                    <TouchableOpacity onPress={() => {
                                        this.setState({
                                            currentBrandIdx: index
                                        })
                                        let params = { selectLevel: 2, from: 'ApplyCarFormPage',  isBrandLimit: true}
                                        AndroidModule.selectBrand(params, (error, result) => {
                                            this.formatBrand(result)
                                        })
                                    }} style={styles.addSelectButton}>

                                        <Text style={styles.addSelectButtonText}>+ 添加{item.type}</Text>
                                    </TouchableOpacity>
                                </View>
                            )
                        }
                        if(item.inputType === 'rangeInput'){
                            return(
                                <View key={index} style={styles.inputGroup}>
                                    <Text style={styles.label}>
                                        {item.isMust === 1 && <Text style={styles.requiredStar}>* </Text>}
                                        {item.typeText}
                                    </Text>
                                    <View style={styles.rangeContainer}>
                                        <TextInput
                                            editable={true}
                                            style={[styles.rangeInput]}
                                            placeholder="不限"
                                            keyboardType="numeric"
                                            value={item.minValue ? item.minValue + '' : ''} // 绑定值
                                            onChangeText={(text) => this.inputValueChange(text, item.inputType, 'minValue', index)}
                                        />
                                        <Text style={styles.rangeText}> - </Text>
                                        <TextInput
                                            editable={true}
                                            style={styles.rangeInput}
                                            placeholder="不限"
                                            keyboardType="numeric"
                                            value={item.maxValue ? item.maxValue + '' : ''} // 绑定值
                                            onChangeText={(text) => this.inputValueChange(text, item.inputType, 'maxValue', index)}
                                        />
                                    </View>
                                </View>
                            )
                        }
                        if(item.inputType === 'rangeSelect'){
                            return (
                                <View key={index} style={styles.inputGroup}>
                                    <Text style={styles.label}>
                                        {item.isMust === 1 && <Text style={styles.requiredStar}>* </Text>}
                                        {item.typeText}
                                    </Text>
                                    <View style={[styles.rangeContainer, {flex: 1}]}>
                                        <TouchableOpacity style={{flex:1}} activeOpacity={0.7}  onPress={() => {
                                            this.showPickerOption(index, item.selectOptions, 'left')
                                        }}>
                                            <TextInput
                                                editable={false}
                                                style={[styles.rangeInput]}
                                                placeholder="不限"
                                                keyboardType="numeric"
                                                value={item.values[0]?.label || ""} // 绑定值
                                            />
                                        </TouchableOpacity>
                                        <Text style={styles.rangeText}> - </Text>
                                        <TouchableOpacity style={{flex:1}} activeOpacity={0.7}  onPress={() => {
                                            this.showPickerOption(index, item.selectOptions, 'right')
                                        }}>
                                            <TextInput
                                                editable={false}
                                                style={styles.rangeInput}
                                                placeholder="不限"
                                                keyboardType="numeric"
                                                value={item.values[1]?.label || ""} // 绑定值
                                            />
                                        </TouchableOpacity>
                                    </View>
                                </View>
                            )
                        }
                        if(item.inputType === 'select'){
                            return (
                                <View key={index} style={styles.inputGroup}>
                                    <Text style={styles.label}>
                                        {item.isMust === 1 && <Text style={styles.requiredStar}>* </Text>}
                                        {item.typeText}
                                    </Text>
                                    <View style={styles.colorOptions}>
                                        {/*<View style={styles.colorOption}>*/}
                                        {/*    <Text style={styles.optionText}>不限</Text>*/}
                                        {/*</View>*/}
                                        {this.selectOptionBtnView(item, index)}
                                        {/*{item.selectOptions.map((opt, optIndex) => (*/}
                                        {/*    <TouchableOpacity key={opt.value} style={styles.colorOption} onPress={() => {*/}
                                        {/*        this.selectOptionBtn(index, optIndex, opt)*/}
                                        {/*    }}>*/}
                                        {/*        <Text>{opt.label}</Text>*/}
                                        {/*    </TouchableOpacity>*/}
                                        {/*))}*/}
                                    </View>
                                </View>
                            )
                        }
                        if(item.inputType === 'uploadImages'){
                            return (
                                <View key={index} style={styles.inputGroup}>
                                    <Text style={styles.label}>
                                        {item.isMust === 1 && <Text style={styles.requiredStar}>* </Text>}
                                        {item.typeText}
                                    </Text>
                                    <View>
                                        <TouchableOpacity
                                            style={styles.imageContainer}
                                            activeOpacity={0.8}
                                            onPress={() => {
                                                this.setState({
                                                    uploadImgIdx: index,
                                                })
                                                this.ActionSheet.show()
                                            }}
                                        >
                                            {
                                                item.values.length > 0 ?
                                                    item.values.map((img, imgIndex) => (
                                                        <View key={imgIndex} style={styles.imgBox}>
                                                            <Image
                                                                style={styles.img}
                                                                source={{
                                                                    uri: getImgUrl(img.value),
                                                                }}
                                                            />
                                                            <TouchableOpacity style={styles.removeImgBox} activeOpacity={0.7} onPress={() => {
                                                                this.removeImg(index, imgIndex)
                                                            }}>
                                                                <Image style={styles.removeImg} source={require('source/image/seekCenter/img_close_icon.png')} />
                                                            </TouchableOpacity>
                                                        </View>

                                                    ))
                                                    : null
                                            }
                                            {item.values.length <= 9 && (
                                                <View style={styles.imgBox}>
                                                    <Image source={require('source/image/add_img_icon.png')} style={styles.img} />
                                                </View>
                                            )}

                                        </TouchableOpacity>
                                    </View>
                                </View>
                            )
                        }

                    })}

                    <View style={{flex:1, height: 30}}></View>
                </ScrollView>

                {/* 固定在底部的发布按钮 */}
                <View style={styles.footer}>
                    <TouchableOpacity style={styles.submitButton} activeOpacity={0.7} onPress={() => {
                        this.saveCarFrom()
                    }}>
                        <Text style={styles.submitButtonText}>确认发布</Text>
                    </TouchableOpacity>
                </View>


                {/* 城市选择 */}
                <RegionPickerView
                    show={this.state.showCityPicker}
                    mode={'pc'}
                    hide={() => {
                        this.setState({
                            showCityPicker: false
                        })
                    }}
                    selectArea={(item) => {
                        this.cityPickerData(item)
                    }}
                />

                {/* 选择器 */}
                {this.state.showPicker && (
                    <View style={{
                        position: 'absolute',
                        left: 0,
                        right: 0,
                        bottom: 0,
                    }}>
                        <CommonPicker
                            pickerData={this.state.pickerData}
                            selectedValue={['']}
                            onPickerConfirm={(names, index) => {
                                this.pickerSure(names)
                            }}
                            onPickerCancel={() => {
                                this.pickerCancel()
                            }}
                            onValueChange={(names, index)=>{
                                console.log('onValueChange', names, index)
                            }}
                        />
                    </View>
                )}

                <ActionSheet
                    ref={o => this.ActionSheet = o}
                    title={'请选择照片来源 ?'}
                    options={['相册', '拍照', '取消']}
                    cancelButtonIndex={2}
                    onPress={(index) => { this.selectPhoto(index) }}
                />

                <PermissionDialog
                    visible={this.state.dialogVisible}
                    onClose={() => this.setDialogVisible(false)}
                    title={'申请相机拍照权限和文件读写存储权限'}
                    content={'申请相机拍照权限，用于上传照片发布求购;申请文件读写权限，用于完成拍照后的图片裁剪保存，完成图片上传'}
                    permissions={[
                        PermissionsAndroid.PERMISSIONS.CAMERA,
                        PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE
                    ]}
                />

                <Loading onRef={ref => (this.Loading = ref)} />

            </View>
        )
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#fff',
    },
    scrollContainer: {
        flex: 1,
    },
    scrollContent: {
        padding: 16,
        paddingBottom: 80, // 给底部按钮留出空间
    },
    header: {
        fontSize: 20,
        fontWeight: 'bold',
        marginBottom: 20,
        textAlign: 'center',
        color: '#333',
    },
    inputGroup: {
        marginBottom: 10,
    },
    label: {
        fontSize: 16,
        fontWeight: 'bold',
        marginBottom: 8,
        marginTop:10,
        color: '#333333',
    },
    input: {
        fontSize: 14,
        height: 40,
        backgroundColor: '#F9F9F9',
        borderRadius: 5,
        paddingLeft: 10,
        color: '#333333',
        width: '100%',
    },
    input2: {
        fontSize: 14,
        height: 40,
        backgroundColor: '#F9F9F9',
        borderRadius: 5,
        paddingLeft: 10,
        color: '#333333',
        width: '100%',
        paddingRight: 50,
    },
    inputCharCount: {
        position: 'absolute',
        right: 5,
        bottom: 5,
        fontSize: 12,
        color: '#999999'
    },
    requiredStar: {
        color: 'red',
        marginRight: 4,
    },
    multilineInput: {
        height: 100,
        textAlignVertical: 'top',
    },
    selector: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        borderWidth: 1,
        borderColor: '#e0e0e0',
        borderRadius: 4,
        padding: 12,
        // backgroundColor: '#fafafa',
    },
    selectorText: {
        fontSize: 14,
        color: '#333',
    },
    arrow: {
        fontSize: 16,
        color: '#999',
    },
    rangeContainer: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
    },
    rangeInput: {
        flex: 1,
        borderRadius: 4,
        padding: 8,
        fontSize: 14,
        backgroundColor: '#F9F9F9',
        height: 40,
    },
    rangeText: {
        fontSize: 14,
        color: '#333',
    },

    rangeInputLeft: {
        marginRight: 10,
    },
    colorOptions: {
        flexDirection: 'row',
        flexWrap: 'wrap',
        marginTop: 5,
    },
    colorOption: {
        borderWidth: 1,
        borderColor: '#e0e0e0',
        borderRadius: 4,
        paddingVertical: 8,
        paddingHorizontal: 12,
        marginRight: 10,
        marginBottom: 10,
        backgroundColor: '#fafafa',
    },
    footer: {
        position: 'absolute',
        bottom: 0,
        left: 0,
        right: 0,
        padding: 20,
        backgroundColor: '#fff',
        borderTopWidth: 1,
        borderTopColor: '#f0f0f0',
    },
    submitButton: {
        backgroundColor: '#FFE000',
        padding: 15,
        borderRadius: 25,
        alignItems: 'center',
    },
    submitButtonText: {
        color: '#fff',
        fontSize: 16,
        fontWeight: 'bold',
    },


    addSelectButton: {
        borderWidth: 1,
        borderColor: '#ffcd00',
        borderRadius: 25,
        paddingVertical: 10,
        paddingHorizontal: 20,
        alignItems: 'center',
        justifyContent: 'center',
        marginTop: 8
    },
    addSelectButtonText: {
        color: '#ffcd00',
        fontSize: 16,
    },

    optionsContainer: {
        flexDirection: 'row',
        flexWrap: 'wrap',
        marginTop: 10,
    },
    optionButton: {
        backgroundColor: '#F5F5F5',
        borderRadius: 20,
        paddingVertical: 8,
        paddingHorizontal: 16,
        margin: 5,
    },
    selectedOption: {
        backgroundColor: '#fff399',
    },
    optionText: {
        fontSize: 14,
        color: '#333333'
    },

    imageContainer: {
        flexDirection: 'row',
        flexWrap: 'wrap',
        marginTop: 10,
    },
    imgBox: {
        width: '33.333%', // 每行三张图片
        aspectRatio: 1, // 正方形比例
        padding: 6,
    },
    img: {
        width: '100%',
        height: '100%',
        borderRadius: 4,
    },
    removeImgBox: {
        position: 'absolute',
        top: -5,
        right: -3
    },
    removeImg:{
        width: 20,
        height: 20,
    },


});

